<template>
  <div class="roles">
    <bread />
    <!-- 卡片式图 -->
    <el-card>
      <el-button type="primary" @click="addRoleDia = true">添加角色</el-button>
      <!-- 表格区域 -->
      <el-table :data="tableData" border style="width1: 100%">
        <el-table-column type="expand">
          <!-- 展开行信息 -->
          <template v-slot="scope">
            <!-- 渲染一级权限 -->
            <el-row
              :class="[
                'tags',
                'rowBottom',
                'rowLift',
                indexx === 0 ? 'rowTop' : '',
              ]"
              v-for="(item, indexx) in scope.row.children"
              :key="item.id"
            >
              <el-col :span="8">
                <el-tag
                  closable
                  effect="dark"
                  @close="removeHead(scope.row, item)"
                >{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="16">
                <el-row
                  :class="[
                    'rowLift',
                    'tags',
                    'rowRigth ',
                    index2 == 0 ? 'rowBottom' : 'rowTop',
                  ]"
                  v-for="(item2, index2) in item.children"
                  :key="item2.id"
                >
                  <!--渲染二级权限 -->
                  <el-col :span="8" class="rowRight">
                    <el-tag
                      type="success"
                      closable
                      @close="removeHead(scope.row, item2)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="15" class="rowRight tags">
                    <!-- 通过for循环嵌套渲染 -->
                    <el-tag
                      type="warning"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeHead(scope.row, item3)"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="姓名"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- 编辑 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row)"
            >编辑</el-button>
            <!-- 删除按钮功能 -->
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="del(scope.row)">删除</el-button>
            <!-- 分配角色-->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="alloc(scope.row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话弹出框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDia" width="30%">
      <el-form
        :model="addruleForm"
        :rules="rules"
        ref="addRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDia = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑当前行角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="editEditt" width="30%">
      <el-form
        :model="editList"
        :rules="rules"
        ref="editRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editEditt = false">取 消</el-button>
        <el-button type="primary" @click="editSure">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配角色" @close="allDia" :visible.sync="allocationDialog" width="40%">
      <el-tree
        :data="list"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="deafks"
        :props="defaultProps"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allocationDialog = false">取 消</el-button>
        <el-button type="primary" @click="allocationSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 导入面包屑导航
import bread from "../bread.vue";
export default {
  components: {
    bread
  },
  data() {
    return {
      //添加用户信息
      addruleForm: {
        roleName: "",
        roleDesc: ""
      },
      //添加用户对话框的开关控制
      addRoleDia: false,

      //表单校验规则
      rules: {
        roleName: {
          required: true,
          message: "请输入角色名称",
          trigger: "blur"
        },
        roleDesc: {
          required: true,
          message: "请输入角色描述",
          trigger: "blur"
        }
      },
      //获取所有数据
      tableData: [],

      // 编辑用户信息
      editList: {},
      editEditt: false,

      // 分配角色数据的了开关
      allocationDialog: false,
      //树形
      defaultProps: {
        children: "children",
        label: "authName"
      },
      allocatId: "",
      //默认被选中的数组
      deafks: [],
      //所有权限数据信息
      list: []
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 分配权限
    // 分配权限对话框控制开关
    allDia() {
      this.deafks = [];
    },
    // 分配权限
    async alloc(item) {
      this.allocatId = item.id;
      const { data: res } = await this.$http.get(`rights/tree`);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.list = res.data;
      /* 
        调用递归，进行传参，将点击当前行信息和保存默认勾选的节点的信息的空数组传入
      */
      this.getKeys(item, this.deafks);
      this.allocationDialog = true;
    },
    // 通过递归的方式,获取角色下所有三级权限的id，并且保存到defkeys中去
    getKeys(node, arr) {
      // 判断当前信息中没有children属性,则证明是三级节点,将其添加到新的数组中
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach(item => this.getKeys(item, arr));
    },

    // 确定按钮提交分配权限，分配权限对话框
    async allocationSure() {
      /*
      
  */
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      // 要求是以字符串形式进行传递
      const idObj = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.allocatId}/rights`,
        {
          rids: idObj
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.allocationDialog = false;
      this.$message.success("分配权限成功");
      this.getRolesList();
    },

    // 点击删除tag标签
    async removeHead(line, item) {
      const confirmText = await this.$confirm(
        "此操作将永久删除该权限?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmText !== "confirm") {
        return this.$message.info("已取消删除！");
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${line.id}/rights/${item.id}`
        );
        console.log(res);
        if (res.meta.status !== 200) {
          this.$message.success(res.meta.msg);
        }
        /*
         
        */
        line.children = res.data;
      }
    },

    // 点击对话框确定按钮，添加用户
    addSubmit() {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(`roles`, this.addruleForm);
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg);
        }
        this.addRoleDia = false;
        this.getRolesList();
      });
    },

    // 点击编辑用户按钮查询
    async editRoles(item) {
      const { data: res } = await this.$http.get(`roles/${item.id}`);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.editList = res.data;
      this.editEditt = true;
    },
    // 提交编辑用户
    editSure() {
      this.$refs.editRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `roles/${this.editList.roleId}`,
          this.editList
        );
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        }
        this.editEditt = false;
        this.getRolesList();
      });
    },

    // 点击删除当前行角色信息
    async del(id) {
      const confirmText = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmText !== "confirm") {
        return this.$message.info("已取消删除！");
      } else {
        const { data: res } = await this.$http.delete(`/roles/${id.id}`);
        if (res.meta.status !== 200) {
          this.$message.success(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.getRolesList();
      }
    },

    // 角色列表数据信息
    async getRolesList() {
      const { data: res } = await this.$http.get(`roles`);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.tableData = res.data;
    }
  }
};
</script>
<style lang="scss" scoped>
.el-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.el-row {
  width: 100%;
  border: right 1px #eee;
}

.tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.rowTop {
  border-top: 1px solid #eee;
}
.rowBottom {
  border-bottom: 1px solid #eee;
}
.rowRigth {
  border-right: 1px solid #eee;
}
.rowLift {
  border-left: 1px solid #eee;
}
</style>
